package com.zym.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zym.entity.Category;
import com.zym.mapper.CategoryMapper;
import com.zym.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
   @Autowired
   private CategoryMapper categoryMapper;
    @Override
    public List<Category> buildTree() {
        List<Category> categoryList = categoryMapper.selectList(null);

        return getTree1(categoryList);
    }


    private List<Category> getTree(List<Category> categoryList){
        List<Category> categoryList1=new ArrayList<>();
        for (Category category :categoryList) {
            if (category.getParentId()==0){
                categoryList1.add(findchildren(categoryList,category));
            }
        }

     return categoryList1;
    }

    private Category findchildren(List<Category> categoryList, Category category) {
        category.setChildren(new ArrayList<>());
        for (Category category1 :categoryList) {
            if (category1.getParentId().equals(category.getCategoryId())){
                category.getChildren().add(findchildren(categoryList,category1));

            }
        }
return  category;
    }



    private List<Category> getTree1(List<Category> categoryList){
        List<Long> collect = categoryList.stream().map(category -> category.getCategoryId()).collect(Collectors.toList());

         List<Category> list=new ArrayList<>();
        for (Category category :categoryList) {
            if (!collect.contains(category.getParentId())){
                list.add(findchildren1(categoryList,category));
            }

        }
        if (list.isEmpty()){
            return categoryList;
        }
        return list;
    }

    private Category findchildren1(List<Category> categoryList, Category category) {
        category.setChildren(new ArrayList<>());
        for (Category category1 :categoryList) {
            if (category1.getParentId().equals(category.getCategoryId())){
                category.getChildren().add(findchildren(categoryList,category1));

            }
        }
        return  category;
    }
}
